<?php

$TOKEN = 'z7GZakz3SHfoGjIc';
$APPID = 'ce6b22f4c1a54c7c9c192f3265fee25c';
$API = 'https://api-sandbox.direct.yandex.ru/api/v4/';
$CAMPAIGN = '4138178';


$DB_SERVER = 'localhost';
$DB_USER = 'root';
$DB_PWD = '00';
$DATABASE = 'fmshop';




$request = array(
		'token'=> $TOKEN,
		'application_id'=> $APPID,
		'login'=> 'fastmagazine',
		'method'=> 'GetBanners',
		'param'=> array('CampaignIDS'=>array($CAMPAIGN)),
		'locale'=> 'ru'
);

$opts = array('http'=>array('method'=>"POST",'content'=>json_encode($request)));
$banners = json_decode(file_get_contents($API, 0, stream_context_create($opts)));

if ($banners->error_code){
	echo $banners->error_str;
	echo "\n";
	die;
}

$c = mysql_connect($DB_SERVER,$DB_USER,$DB_PWD);
mysql_query('use '.$DATABASE,$c);
mysql_query("set names 'utf-8'");

foreach ($banners->data as $banner){
	$res = mysql_query('select article from yandex_direct where banner = \''.$banner->BannerID.'\'',$c);
	$exists = mysql_fetch_assoc($res);
	mysql_free_result($res);
	
	if ($exists !== false){
		$slug = substr($banner->Href,strrpos($banner->Href, '/'));
		echo $slug;
		
		$minus = mysql_escape_string(join(';',$banner->MinusKeywords));
		
		$stage = 'PUB';
		switch ($banner->StatusBannerModerate){
			case 'Pending':$stage = 'MOD';
			case 'Yes':$stage = 'STP';
		}
		if ($banner->StatusShow == 'Yes')
			$stage = 'RES';
		
		$phrases = array();
		foreach ($banner->Phrases as $phrase)
			$phrases[$phrase->PhraseID] = $phrase->Phrase;
		
		$phrases = mysql_escape_string(json_encode($phrases));
		
		mysql_query("
			insert yandex_direct (article,banner,campaign,title,advtext,minus_keywords,phrases,stage)
				select pp.product,'$banner->BannerID','$banner->CampaignID','".mysql_escape_string($banner->Title)."','".mysql_escape_string($banner->Text)."','$minus','$phrases','$stage'
				from product_page pp inner join page p on p.pid = pp.pid
				where p.slug = '".mysql_escape_string($slug)."'");
		
		echo "....done\n";
	}
}